package Schedule;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.primefaces.event.ScheduleEntryMoveEvent;
import org.primefaces.event.ScheduleEntryResizeEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultScheduleEvent;
import org.primefaces.model.DefaultScheduleModel;
import org.primefaces.model.ScheduleEvent;
import org.primefaces.model.ScheduleModel;

@ManagedBean
@ViewScoped
public class AgendaUpper extends DefaultScheduleEvent implements Serializable {

    private ScheduleModel eventModel;

    private ScheduleModel lazyEventModel;

    private ScheduleEvent event = new DefaultScheduleEvent();

    private String ex;

    private String descricao;

    private boolean btnExcluir = false;

    public AgendaUpper(String descricao, String title, Date start, Date end, Object data) {
        super(title, start, end, data);
        this.descricao = descricao;
    }

    public AgendaUpper() {
        super();

        eventModel = new DefaultScheduleModel();

        try {

            Class.forName("com.mysql.jdbc.Driver");
            Connection conexao;
            Statement stm;
            ResultSet resultado;
            //PreparedStatement a;

            String url, usuario, senha, sql;
            url = "jdbc:mysql://localhost:3306/sigupper";
            usuario = "root";
            senha = "impacta";

            conexao = DriverManager.getConnection(url, usuario, senha);
            stm = conexao.createStatement();
            sql = "select * from agenda a inner join cliente c on a.cliente_id=c.clienteId";
            resultado = stm.executeQuery(sql);

            while (resultado.next()) {

                String e = resultado.getString(String.valueOf("a.agenda_id"));
                String a = resultado.getString("c.cliente_nome");
                String b = resultado.getString("a.agenda_dtini");
                String c = resultado.getString("a.agenda_dtfim");
                String f = resultado.getString("a.agenda_descricao");

                long agenda_dtini = Long.parseLong(b);
                long agenda_dtfim = Long.parseLong(c);

                eventModel.addEvent(new AgendaUpper(f, a, new Date(agenda_dtini), new Date(agenda_dtfim), Integer.parseInt(e)));

                //eventos.add(new DefaultScheduleEvent(a, new Date(agenda_dtini), new Date(agenda_dtfim), diaTodo));
            }

            conexao.close();

        } catch (java.sql.SQLException | java.lang.ClassNotFoundException Ex) {
            System.out.println(Ex.getMessage());
        }

    }

    public Date getRandomDate(Date base) {
        Calendar date = Calendar.getInstance();
        date.setTime(base);
        date.add(Calendar.DATE, ((int) (Math.random() * 30)) + 1);    //set random day of month

        return date.getTime();
    }

    public Date getInitialDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), Calendar.FEBRUARY, calendar.get(Calendar.DATE), 0, 0, 0);

        return calendar.getTime();
    }

    public ScheduleModel getEventModel() {
        return eventModel;
    }

    public ScheduleModel getLazyEventModel() {
        return lazyEventModel;
    }

    private Calendar today() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 0, 0, 0);

        return calendar;
    }

    private Date previousDay8Pm() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.AM_PM, Calendar.PM);
        t.set(Calendar.DATE, t.get(Calendar.DATE) - 1);
        t.set(Calendar.HOUR, 8);

        return t.getTime();
    }

    private Date previousDay11Pm() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.AM_PM, Calendar.PM);
        t.set(Calendar.DATE, t.get(Calendar.DATE) - 1);
        t.set(Calendar.HOUR, 11);

        return t.getTime();
    }

    private Date today1Pm() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.AM_PM, Calendar.PM);
        t.set(Calendar.HOUR, 1);

        return t.getTime();
    }

    private Date theDayAfter3Pm() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.DATE, t.get(Calendar.DATE) + 2);
        t.set(Calendar.AM_PM, Calendar.PM);
        t.set(Calendar.HOUR, 3);

        return t.getTime();
    }

    private Date today6Pm() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.AM_PM, Calendar.PM);
        t.set(Calendar.HOUR, 6);

        return t.getTime();
    }

    private Date nextDay9Am() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.AM_PM, Calendar.AM);
        t.set(Calendar.DATE, t.get(Calendar.DATE) + 1);
        t.set(Calendar.HOUR, 9);

        return t.getTime();
    }

    private Date nextDay11Am() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.AM_PM, Calendar.AM);
        t.set(Calendar.DATE, t.get(Calendar.DATE) + 1);
        t.set(Calendar.HOUR, 11);

        return t.getTime();
    }

    private Date fourDaysLater3pm() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.AM_PM, Calendar.PM);
        t.set(Calendar.DATE, t.get(Calendar.DATE) + 4);
        t.set(Calendar.HOUR, 3);

        return t.getTime();
    }

    public ScheduleEvent getEvent() {
        return event;
    }

    public void setEvent(ScheduleEvent event) {
        this.event = event;
    }

    public void addEvent(ActionEvent actionEvent) {

        if (event.getStartDate().getTime() <= event.getEndDate().getTime()) {

            try {

                Class.forName("com.mysql.jdbc.Driver");
                Connection conexao;
                Statement stm;
                //PreparedStatement a;

                String url, usuario, senha, sql;
                url = "jdbc:mysql://localhost:3306/sigupper";
                usuario = "root";
                senha = "impacta";

                conexao = DriverManager.getConnection(url, usuario, senha);
                stm = conexao.createStatement();

                if (event.getData() == null) {
                    eventModel.addEvent(event);
                    sql = "INSERT INTO agenda (cliente_id, agenda_dtini, agenda_dtfim, agenda_descricao) VALUES('" 
                            + Integer.parseInt(event.getTitle()) + "','" 
                            + event.getStartDate().getTime() + "', '" 
                            + event.getEndDate().getTime() + "', '" 
                            + getDescricao() + "')";

                } else {
                    eventModel.updateEvent(event);
                    sql = "UPDATE agenda SET cliente_id='" + Integer.parseInt(event.getTitle())
                            + "', agenda_dtini='" + event.getStartDate().getTime()
                            + "', agenda_dtfim='" + event.getEndDate().getTime()
                            + "', agenda_descricao='" + getDescricao()
                            + "' where agenda_id='" + event.getData() + "'";

                }

                stm.execute(sql);
                conexao.close();

            } catch (java.sql.SQLException | java.lang.ClassNotFoundException Ex) {
                System.out.println(Ex.getMessage());
            }
        }

        event = new DefaultScheduleEvent();

    }

    public void onEventSelect(SelectEvent selectEvent) {
        event = (ScheduleEvent) selectEvent.getObject();

    }

    public void onDateSelect(SelectEvent selectEvent) {
        event = new DefaultScheduleEvent("", (Date) selectEvent.getObject(), (Date) selectEvent.getObject());
    }

    public void onEventMove(ScheduleEntryMoveEvent event) {

        if (event.getScheduleEvent().getStartDate().getTime() <= event.getScheduleEvent().getEndDate().getTime()) {

            try {

                Class.forName("com.mysql.jdbc.Driver");
                Connection conexao;
                Statement stm;
                //PreparedStatement a;

                String url, usuario, senha, sql;
                url = "jdbc:mysql://localhost:3306/sigupper";
                usuario = "root";
                senha = "impacta";

                conexao = DriverManager.getConnection(url, usuario, senha);
                stm = conexao.createStatement();

                sql = "UPDATE agenda SET agenda_dtini='" + event.getScheduleEvent().getStartDate().getTime()
                        + "', agenda_dtfim='" + event.getScheduleEvent().getEndDate().getTime()
                        + "' where agenda_id='" + event.getScheduleEvent().getData() + "'";

                stm.execute(sql);
                conexao.close();

            } catch (java.sql.SQLException | java.lang.ClassNotFoundException Ex) {
                System.out.println(Ex.getMessage());
            }
        }

    }

    public void onEventResize(ScheduleEntryResizeEvent event) {

        try {

            Class.forName("com.mysql.jdbc.Driver");
            Connection conexao;
            Statement stm;
            //PreparedStatement a;

            String url, usuario, senha, sql;
            url = "jdbc:mysql://localhost:3306/sigupper";
            usuario = "root";
            senha = "impacta";

            conexao = DriverManager.getConnection(url, usuario, senha);
            stm = conexao.createStatement();

            sql = "UPDATE agenda SET agenda_dtini='" + event.getScheduleEvent().getStartDate().getTime()
                    + "', agenda_dtfim='" + event.getScheduleEvent().getEndDate().getTime()
                    + "' where agenda_id='" + event.getScheduleEvent().getData() + "'";

            stm.execute(sql);
            conexao.close();

        } catch (java.sql.SQLException | java.lang.ClassNotFoundException Ex) {
            System.out.println(Ex.getMessage());
        }

    }

    private void addMessage(FacesMessage message) {
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

    public void removeEvent() {

        try {

            Class.forName("com.mysql.jdbc.Driver");
            Connection conexao;
            Statement stm;
            //PreparedStatement a;

            String url, usuario, senha, sql;
            url = "jdbc:mysql://localhost:3306/sigupper";
            usuario = "root";
            senha = "impacta";

            conexao = DriverManager.getConnection(url, usuario, senha);
            stm = conexao.createStatement();

            sql = "DELETE FROM agenda WHERE agenda_id='" + event.getData() + "'";
            /*
             sql = "UPDATE agenda SET cliente_cliente_id='" + event.getStartDate() + "' where cliente_cliente_id='" + event.getTitle()+ "'";
             */
            stm.execute(sql);
            conexao.close();

        } catch (java.sql.SQLException | java.lang.ClassNotFoundException Ex) {
            System.out.println(Ex.getMessage());
        }

    }

    public boolean isBtnExcluir() {
        return btnExcluir;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public String getDescricao() {
        return descricao;
    }

}
